package com.parking.certified.service.config;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.parking.certified.exception.CertifiedException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

/**
 * 经纬度工具包
 */
@Component
public class MapUtil {
    private static final double EARTH_RADIUS = 6371; // 地球半径，单位为千米
    /**
     * 根据地址获取经纬度
     * @param address 地址参数
     */

    public static AddressLocation getAddressLocation(String address) throws Exception {
        HttpClient httpClient = HttpClientBuilder.create().build();
        AddressLocation addressLocation = new AddressLocation();
        String url = "https://restapi.amap.com/v3/geocode/geo?key=fd0d34ed5c857134f14ccbc4672da9f3&address=" + address;
        HttpGet request = new HttpGet(url);
        HttpResponse response = httpClient.execute(request);
        HttpEntity entity = response.getEntity();
        String responseString = EntityUtils.toString(entity);
        System.out.println(responseString);
        JSONObject object = new JSONObject(responseString);
        JSONArray geocodes = object.getJSONArray("geocodes");
        if (geocodes == null) throw new CertifiedException( "未找到该地址",600);
        if (geocodes.size() > 0) {
            String location = geocodes.getJSONObject(0).getStr("location").toString();
            String[] split = location.split(",");
            addressLocation.setLongitude(Double.valueOf(split[0]));
            addressLocation.setLatitude(Double.valueOf(split[1]));
        } else {
            throw new CertifiedException("未找到该地址的经纬度信息",600);
        }
        return addressLocation;
    }
    /**
     * 计算两个经纬度的地理位置的距离
     * @param lat1
     * @param lon1
     * @param lat2
     * @param lon2
     */

    public static Double calculateDistance(double lat1, double lon1, double lat2, double lon2) {
        double dLat = Math.toRadians(lat2 - lat1);
        double dLon = Math.toRadians(lon2 - lon1);

        double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
                Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
                        Math.sin(dLon / 2) * Math.sin(dLon / 2);

        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

        double distance = EARTH_RADIUS * c;

        return Double.valueOf(distance);
    }

}
